package com.zx.dsptuneup_cloud.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.google.android.material.tabs.TabLayout;
import com.zx.dsptuneup_cloud.App;
import com.zx.dsptuneup_cloud.Base.BaseFragment;
import com.zx.dsptuneup_cloud.Common.DrawableTextView;
import com.zx.dsptuneup_cloud.Common.SlideToggleView;
import com.zx.dsptuneup_cloud.Enum.MessageReceiveType;
import com.zx.dsptuneup_cloud.ProtocolTools.ProtocolConversion;
import com.zx.dsptuneup_cloud.R;
import com.zx.dsptuneup_cloud.Tools.ChannelIndexConvert;
import com.zx.dsptuneup_cloud.Tools.Constant;
import com.zx.dsptuneup_cloud.Tools.EventMessage;
import com.zx.dsptuneup_cloud.Util.ClickUtil;
import com.zx.dsptuneup_cloud.Util.Constants;
import com.zx.dsptuneup_cloud.Util.UserUtil;
import com.zx.dsptuneup_cloud.widget.ui.MyWhiteTabLayout;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class InputFragment extends BaseFragment {

    @BindView(R.id.tableLayout)
    MyWhiteTabLayout tabLayout;

    @BindView(R.id.slideBtn)
    SlideToggleView slideView;

    @BindView(R.id.muteBtn)
    DrawableTextView muteBtn;

    @BindView(R.id.micBtn)
    DrawableTextView micBtn;

    @BindView(R.id.circle_eq_switch_Layout)
    RelativeLayout circle_eq_switch_Layout;
    //   data
    private String TAG = "InputFragment";

    private int currentSelTitleIndex = Constants.channelEnum.line1;       //  头部标签选择
    private List<String> titleArr = new ArrayList<>();
    private String[] developArr = {"吊麦1","阵列麦1","吊麦2","阵列麦2","吊麦3","阵列麦3","模拟桌麦","线路1","会议通道","啸叫返回","保留","线路2","数字桌麦1"};
    private String[] userArr = {"吊麦1","吊麦2","吊麦3","桌麦1","线路","会议通道","桌麦2"};
//    private boolean[] passagewayBoolArr = {false,false,false,false,false,false,false,false,false,false,false,false,false,false}; //静音开关
    private int[] developChannelArr = {Constants.channelEnum.line1,Constants.channelEnum.line2,
            Constants.channelEnum.line3,Constants.channelEnum.line4,Constants.channelEnum.line5,
            Constants.channelEnum.line6,Constants.channelEnum.line7,Constants.channelEnum.line8,
            Constants.channelEnum.line9,Constants.channelEnum.line10,Constants.channelEnum.line11,
            Constants.channelEnum.line12,Constants.channelEnum.line13,Constants.channelEnum.line14}; // 对应开发者通道数据

    private int[] userChannelArr = {Constants.channelEnum.line1,Constants.channelEnum.line3,
            Constants.channelEnum.line5,Constants.channelEnum.line7, Constants.channelEnum.line8,
            Constants.channelEnum.line9,Constants.channelEnum.line13};                             // 对应普通用户通道数据


    //   view
    private View rootView;
    /**
     *  gain 和eq fragment
     * */
    private InputEQFragment           inputEQFragment = new InputEQFragment();
    private InputGainFragment       inputGainFragment = new InputGainFragment();
    private InputDevelopFragment inputDevelopFragment = new InputDevelopFragment();

    public InputFragment() {
        setFragmentTitle(App.getContext().getString(R.string.input));
    }

    @Override
    public void onResume() {
        super.onResume();
        // 设置返回页面，更换fragment
        titleArr.clear();
        if(slideView.getToggleState()){
            if(UserUtil.isDevelopMode){
                replaceFragment(inputDevelopFragment);
            }else {
                replaceFragment(inputEQFragment);
            }
        }


        Log.e(TAG,"currentSelTitleIndex==="+currentSelTitleIndex);

        if(UserUtil.isDevelopMode){
            //  需要做转换，否则调用Arrays.asList()生产的List的add、remove方法时报异常
            List<String> list = Arrays.asList(developArr);
            titleArr = new ArrayList(list);
            if(currentSelTitleIndex == 8){
                micBtn.setVisibility(View.VISIBLE);
            }else {
                micBtn.setVisibility(View.INVISIBLE);
            }

        }else {
            List<String> list = Arrays.asList(userArr);
            titleArr = new ArrayList(list);

            if(currentSelTitleIndex == 5){
                micBtn.setVisibility(View.VISIBLE);
            }else {
                micBtn.setVisibility(View.INVISIBLE);
            }
        }
        tabLayout.refreshTitles(titleArr);
        //  刷新了title自动选中

        // 下面代码要放在刷新tab 后面执行,用于页面跳转之后,tab下面数据刷新判断
        currentSelTitleIndex = Constants.channelEnum.line1;

    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    protected void initData() {}

    @Override
    protected void initVariables(Bundle bundle) { }

    private void setupData() {
        //  初始化titlArr
        if(UserUtil.isDevelopMode){
            titleArr.add("通道1");
        }else {
            titleArr.add("通道1");
        }
        tabLayout.setTitle(titleArr);
        tabLayout.getTabAt(0).select();
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Log.e(TAG,"onTabSelected");
                int position = tab.getPosition();

                if(position == currentSelTitleIndex){
                    return;
                }
                currentSelTitleIndex = position;
                //  发送事件
                EventMessage msg = new EventMessage(MessageReceiveType.InputTitleIndexChange, position+"");
//                EventBus.getDefault().post(msg);
                EventBus.getDefault().postSticky(msg);
                //  切换的ui处理在各自的fragment处理

                // 处理一下普通和开发者的index区别
                int posotion = ChannelIndexConvert.convertIndex(currentSelTitleIndex);

                //  设置麦克风状态
                boolean isMute =  App.getContext().getEqData().getInputChannelArr().get(posotion).isMute();
                String micSta = isMute ? "静音" : "恢复";

                muteBtn.setSelected(isMute);
                muteBtn.setText(micSta);

                if(UserUtil.isDevelopMode){
                    if(currentSelTitleIndex == 8){
                        micBtn.setVisibility(View.VISIBLE);
                    }else {
                        micBtn.setVisibility(View.INVISIBLE);
                    }
                }else {
                    if(currentSelTitleIndex == 5){
                        micBtn.setVisibility(View.VISIBLE);
                    }else {
                        micBtn.setVisibility(View.INVISIBLE);
                    }
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });


        // gain和eq选择开关
//        slideView.setToggleState(false);
        replaceFragment(new InputGainFragment());
        slideView.setOnToggleChangeListener(new SlideToggleView.OnToggleChangeListener() {
            @Override
            public void onToggleChange(View view, boolean open) {
                if(open){
                    if(UserUtil.isDevelopMode){
                        replaceFragment(inputDevelopFragment);
                    }else {
                        replaceFragment(inputEQFragment);
                    }
                }else{
                    replaceFragment(inputGainFragment);
                }
            }
        });
        slideView.setToggleState(false);

        muteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                muteBtn.setSelected(!muteBtn.isSelected());
                if(muteBtn.isSelected()){
                    muteBtn.setText("静音");
                }else{
                    muteBtn.setText("恢复");
                }
                int posotion = ChannelIndexConvert.convertIndex(currentSelTitleIndex);
                App.getEqData().getInputChannelArr().get(posotion).setMute(muteBtn.isSelected());

//                passagewayBoolArr[currentSelTitleIndex] = muteBtn.isSelected();

                int channel;
                if(UserUtil.isDevelopMode){
                    channel = developChannelArr[currentSelTitleIndex];
                }else {
                    channel = userChannelArr[currentSelTitleIndex];
                }
               // App.getContext().getProtocolConversion().setMute(ProtocolConversion.getFrameId(), Constants.operation_typeEnum.set_device,Constants.element_typeEnum.INPUT, channel,muteBtn.isSelected());

                App.getContext().getProtocolServiceUtil().setInputMuteParameterData(channel, Constants.inputAndOutput_event_typeEnum.MUTE,muteBtn.isSelected());
                Intent intent = new Intent(Constant.updateNum);
                getActivity().sendBroadcast(intent);

            }
        });

        //  远程会议开启
        micBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                micBtn.setSelected(!micBtn.isSelected());
                if(micBtn.isSelected()){
                    micBtn.setText("远程关闭");
                    App.getContext().getProtocolServiceUtil().setRemote("00");
                }else{
                    micBtn.setText("远程开启");
                    App.getContext().getProtocolServiceUtil().setRemote("01");
                }

                Intent intent = new Intent(Constant.updateNum);
                getActivity().sendBroadcast(intent);
                //App.getContext().getProtocolConversion().setMuteXmose(ProtocolConversion.getFrameId(),Constants.operation_typeEnum.set_device,Constants.element_typeEnum.MUTEXmose, micBtn.isSelected());
            }
        });
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_input, container, false);
            ButterKnife.bind(this, rootView);
            EventBus.getDefault().register(this);
            setupData();
        }

        return rootView;
    }

    private void replaceFragment(BaseFragment fragment){
        FragmentManager fragmentManager = getChildFragmentManager();//这里获取碎片管理器的方法不同于碎片中嵌套碎片这里使用的是getSupportFragmentManager（）  注：貌似这里亦可以用getFragmentManager（）
        FragmentTransaction transaction = fragmentManager.beginTransaction();//开启一个事物，通过调用beginTransaction（）开启

        transaction.replace(R.id.circle_eq_switch_Layout,fragment);//向容器内替换碎片（添加用.add）  第一个参数：容器id  第二个参数：待添加的碎片
        transaction.commit();//提交事务
    }

    /**
     *  收到消息
     * */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGetStickyEvent(EventMessage message) {
        Log.d(TAG,"onReceiveMsg====" + message.toString());
        if (message.getType().equals(MessageReceiveType.MessageRecMuteX)){
            //  设置互斥/远程互动状态
            boolean isMute =  App.getContext().getEqData().isMuteXSta() ;
            String micSta = isMute ? "远程关闭" : "远程开启";

            micBtn.setSelected(isMute);
            micBtn.setText(micSta);
        }else if(message.getType().equals(MessageReceiveType.MessageRecInput)){
            // 读取的时候 普通用户模式 需要做转换 取值的位置不同

            int posotion = ChannelIndexConvert.convertIndex(currentSelTitleIndex);

            //  设置通道静音状态
            boolean isMute =  App.getContext().getEqData().getInputChannelArr().get(posotion).isMute();
            String micSta = isMute ? "静音" : "恢复";

            muteBtn.setSelected(isMute);
            muteBtn.setText(micSta);
        }
    }

    /**
     * dp转换成px
     */
    public int dp2px(float dpValue){
        float scale=getResources().getDisplayMetrics().density;
        return (int)(dpValue*scale+0.5f);
    }

    @Override
    public void onClick(View v) {
        if (ClickUtil.isFastClick(1000, v)) {
            return;
        }
    }
}
